//
//  TLOauthViewController.swift
//  TLSinaWeiBo
//
//  Created by 谭亮 on 16/5/14.
//  Copyright © 2016年 tanliang. All rights reserved.
//

import UIKit
import SVProgressHUD
class TLOauthViewController: UIViewController {

    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = GlobalBKGColor//:没设置前我这也是白色的
        
        
        
        //:->设置导航栏
        //:->左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofill")
        
        //:->右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        //:-> title
        navigationItem.title = "登录"
        
        //:使用webView加载登录界面
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        TLPrint(items: "urlString: \(urlString)")
        
        //:->加指示器,显示正在加载
        //SVProgressHUD.showErrorWithStatus(<#T##status: String!##String!#>) 显示错误
        //SVProgressHUD.showInfoWithStatus("正在加载")//:提示信息感叹号.会自动关闭提示信息.
        SVProgressHUD.showWithStatus("正在加载")//:进度形式,如果不主动关闭会一直存在
        
    }

    // MARK: - 点击事件
    @objc private func autofill() {
        
        TLPrint(items: "")
        let jsString = "document.getElementById('userId').value = 'tanliangjiade@gmail.com';document.getElementById('passwd').value = 'gbzjtanLove';"
        //:->WebView执行JS代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    //:取消
    @objc private func close() {
        //:取消时也要关闭
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 懒加载
    /// webView
    private lazy var webView: UIWebView = UIWebView()
    
}

extension TLOauthViewController: UIWebViewDelegate {
    //:webView加载完成调用
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //:->webView加载网页的时候会调用这个方法,加载一次回调一次,询问我们是否要加载某个请求
    //:return true 可以加载这个界面
    //:return false 就不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!
        TLPrint(items: "request: \(request.URL) ")
        
        //:->点击授权加载 http://www.sina.com/?code=9dd895e0fc4ce20448f27421f154cf70
        //:->点击取消 http://www.sina.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        if !url.absoluteString.hasPrefix(redirect_uri) {
            //:->只要不是授权地址 是新浪微博的界面  就让它去加载
            return true
        } else {
        //:是授权回调地址,点击的是取消或授权,不让他去加载.我们自己来做一些事情
        //:URL的query查询: >后面的东西
            let query = url.query!
            // TLPrint(items: "点击了授权或取消")
            //TLPrint(items: "query: \(query)")
            let codeString = "code="
            if query.hasPrefix(codeString) {
                //:如果query 是以 code= 开头表示点击的授权登录按钮 
                //  TLPrint(items: "点击了授权按钮")
                
                //:->从query中截取code的值,substringFormIndex从指定位置截取到最后
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                TLPrint(items: "code: \(code)")
                
                /// 加载AccessToken,字典转模型,模型保存到沙盒
                TLUserAccountViewModel.sharesInstance.loadAccessToken(code, callback: { (error) -> () in
                    if error != nil {
                        //出现了错误
                        TLPrint(items: "出现了错误: \(error)")
                        SVProgressHUD.showErrorWithStatus("您的网络不给力...")
                        // 延迟一秒关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        
                    } else {
                        // 没有错误
                        //TLPrint(items: "没有出现错误")
                    }
                })
            }
            else {
                //:点击的是取消按钮
                TLPrint(items: "点击了取消按钮")
                close()
            }
            
            return false
        }
    }
}
